/*
 * Copyright (c) 2021-present, the hapjs-platform Project Contributors
 * SPDX-License-Identifier: Apache-2.0
 */
const prompt = require('@system.prompt')
const router = require('@system.router')
const fetch = require('@system.fetch')
const image = require('@system.image')
const app = require('@system.app')

export function paramsString(params) {
  if (!params) return ''
  const str = []
  for (let key in params) {
    if (![undefined, null, ''].includes(params[key])) {
      str.push(key + '=' + params[key])
    }
  }
  const paramStr = str.join('&')
  return paramStr
}

function queryString(url, query) {
  let str = []
  for (let key in query) {
    str.push(key + '=' + query[key])
  }
  let paramStr = str.join('&')
  return paramStr ? `${url}?${paramStr}` : url
}

function getQueryParams(url) {
  const queryString = url.split('?')[1]
  const queryObj = {}
  if (queryString) {
    // 4. 分割每个参数对
    const params = queryString.split('&')
    params.forEach(param => {
      const [key, value] = param.split('=')
      queryObj[decodeURIComponent(key)] = decodeURIComponent(value)
    })
  }

  return queryObj
}

function showToast(message = '', duration = 0) {
  if (!message) return
  prompt.showToast({
    message: message,
    duration
  })
}
function turnback() {
  router.back()
}
function formatDate(date, symbols = '-') {
  date = new Date(date)
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  let d = date.getDate()
  d = d < 10 ? '0' + d : d
  const monthDay = symbols == 'zh' ? m + '月' + d + '日' : m + symbols + d
  let w = date.getDay()
  let h = date.getHours()
  h = h < 10 ? '0' + h : h
  let min = date.getMinutes()
  min = min < 10 ? '0' + min : min
  const hoursMinutes = h + ':' + min
  const week = '周' + ['日', '一', '二', '三', '四', '五', '六'][w]
  const yearMonthDay = symbols == 'zh' ? y + '年' + m + '月' + d + '日' : y + symbols + m + symbols + d

  return {
    hoursMinutes,
    week,
    monthDay,
    yearMonthDay
  }
}
function isNumber(value) {
  return /^[0-9]$/.test(value)
}
function calculateMinutes(t1, t2) {
  // 将时间戳转换为Date对象
  const date1 = Number(t1)
  const date2 = Number(t2)
  // 计算时间差（毫秒）
  const timeDifference = Math.abs(date1 - date2)
  // 将毫秒转换为分钟
  const minutesDifference = Math.floor(timeDifference / (1000 * 60))
  // console.error(date1,date2,timeDifference,minutesDifference)
  return minutesDifference
}

export function getOrderData(obj, globalKey) {
  const keys = Object.keys(obj)
  const globalIndex = getGlobalData(globalKey)
  const indexCurrent = globalIndex >= 0 && globalIndex < keys.length - 1 ? globalIndex + 1 : 0
  const key = keys[indexCurrent]
  setGlobalData(globalKey, indexCurrent)
  return obj[key]
}

function getRandomNumber(n) {
  return Math.floor(Math.random() * (n + 1))
}

export function getRandomData(obj) {
  const keys = Object.keys(obj)
  const randomKeyIndex = getRandomNumber(keys.length - 1)
  const randomKey = keys[randomKeyIndex]

  return obj[randomKey]
}

// 从数组中任意获取一个元素
export function getRandomElement(arr) {
  if (arr.length === 0) {
    return undefined
  }
  const randomIndex = Math.floor(Math.random() * arr.length)
  return arr[randomIndex]
}

export function genUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (Math.random() * 16) | 0,
      v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

export function routerOpenApp({ pkgname, path, params }) {
  router.push({
    uri: `hap://app/${pkgname}/${path || ''}`,
    params
  })
}

export function iframeOpenApp({ pkgname, path, params }) {
  let str = paramsString(params)
  str += '&__E_source__=21&__xiaomi_session__=' + genUUID() + '&url_origin_top=https%3A%2F%2Fhapjs.org&url_is_top=true' //该行固定值
  const timestamp = Date.now() * 1000
  const url =
    'http://qallzmx.quickapp.cn/?i=' +
    pkgname +
    '&p=' +
    path +
    '&random=' +
    Math.random() +
    '&a=' +
    encodeURIComponent(str)
  console.log(url, 'url')
  let r = {
    url,
    header: {
      Host: 'qallzmx.quickapp.cn',
      Referer:
        'https://statres.quickapp.cn/quickapp/js/btn.html?iframeIndex=0&fontSize=5.92593&startTime=' +
        timestamp +
        '&pkg=' +
        pkgname,
      'User-Agent':
        'Mozilla/5.0 (Linux; Android 13; 23049RAD8C Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/108.0.5359.128 Mobile Safari/537.36'
    }
  }

  fetch.fetch(r)
}

export function iframeOpenAppWidthHighVersionInXiaomi({ pkgname, path, params }) {
  return new Promise(resolve => {
    image.editImage({
      uri: 'internal://cache/123.png',
      success: function(data) {
        console.log(`handling success: ${data}`)
      },
      fail: function(data, code) {
        console.log(`handling fail, code = ${code}, data = ${data}`)
      },
      complete: () => {
        iframeOpenApp({ pkgname, path, params })
        resolve(true)
      }
    })
  })
}

export const isSamPkg = pkg => {
  const appInfo = app.getInfo()
  return pkg === appInfo.packageName
}

function getFormattedDate() {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

export default {
  showToast,
  queryString,
  getQueryParams,
  formatDate,
  turnback,
  isNumber,
  calculateMinutes,
  getRandomNumber,
  getRandomData,
  getRandomElement,
  getOrderData,
  routerOpenApp,
  iframeOpenApp,
  iframeOpenAppWidthHighVersionInXiaomi,
  isSamPkg,
  getFormattedDate
}
